<?php

jimport('joomla.application.component.controller');

class bgController extends JController {
    public function __construct(){
        parent::__construct();
        $this->model = $this->getModel();

    }
    
    /* save */
    public function save(){
        $data = &JRequest::getVar('jform');
        if($this->getModel()->checkExistID($data['BANNER_CODE'])){
            $addNew = false;
        }
        else{
            $addNew = true;
        }
        
        if(!empty($_FILES['jformBANNER_IMG']['name'])){
            $data['BANNER_IMG'] = $_FILES['jformBANNER_IMG']['name'];
            move_uploaded_file($_FILES["jformBANNER_IMG"]["tmp_name"],"uploads/images/com_msbanner/" . $_FILES["jformBANNER_IMG"]["name"]);
            
            // doi lai ten
            $img_old = $_FILES['jformBANNER_IMG']['name'];
            $img = explode(".",$img_old);
            $extend = $img[count($img)-1];
            $path_source_old = "uploads/images/com_msbanner/".$img_old;
            $nowtime = time();
            $img_new = $data['BANNER_CODE'].'_'.$nowtime.".".$extend;
            $path_source_new = "uploads/images/com_msbanner/".$img_new;
            if(file_exists($path_source_old)){
                rename($path_source_old,$path_source_new);
                $data['BANNER_IMG'] = $img_new;
            }
              
        }else{
                $data['BANNER_IMG'] = $data['BANNER_IMG_old'];    
        }
        
        /* save data */  
        if($this->model->save($data,$addNew)){
            $this->setRedirect('index.php?option=com_msbanner');
        }else{
            $error = "エラー！データが記録されません。";
            JRequest::setVar('task','');
            JFactory::getApplication()->enqueueMessage($error, 'error');
        }
         
        parent::display();
    }
    
    /* remove records banner */
    public function remove(){
    	$cid = JRequest::getVar('cid');  
        
        foreach($cid as $value){
            //get image name
            $img_name = $this->getModel()->getImgFromBannerCode($value);
            //Del Image
            if($img_name != null){
                $path = "uploads/images/com_msbanner/$img_name";
                if(file_exists($path)){
                    $del = unlink($path);
                }
            }
        }
             
        $this->model->remove($cid);
        $this->setRedirect('index.php?option=com_msbanner'); 
    }

}